﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Bricks.Business.Service.Impl;
using Bricks.Site.Models;
using Bricks.Business.Models.FlowProcess;
using System.Xml;
using System.Web.Script.Serialization;
using Bricks.Business.Service;
using Bricks.Component.Utils;
using Bricks.Site.Web.CommonUtils;
using Bricks.Component.Utils.Extensions;
using Bricks.Business.Models.ProjectContract;
using Bricks.Business.Service.CommonSupport;
using Bricks.Business.Models.SafetyManagement;

namespace Bricks.Site.Web.Controllers
{
    [Export]
    public class EnvironmentalController : BaseController
    {
        [Import]
        public IEnvironmentalService EnvironmentalService { get; set; }
        [Import]
        public ICommonContractInfoService CommonContractInfoService { get; set; }

        [Import]
        public ISystemProcessMessageService SystemProcessMessageService { get; set; }

        [Import]
        public IOrgInfoService OrgInfoService { get; set; }

        [Import]
        public IUserOrgService UserOrgService { get; set; }

        //[Import]
        //public IBidInfoService BidInfoService { get; set; }

        [Import]
        public IContractInfoService ContractInfoService { get; set; }

        [Import]
        public IDocumentService DocumentService { get; set; }

        //public ActionResult CircularList()
        //{
        //    return Json(EnvironmentalService.GetCircularList(), JsonRequestBehavior.AllowGet);
        //}

        public ActionResult Index()
        {
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDataList(int rows = 20, int page = 1)
        {
            var queryData = EnvironmentalService.Environmentals.OrderByDescending(m => m.PublishTime).Skip(rows * (page - 1)).Take(rows).ToList();
            var list = from m in queryData
                       select new EnvironmentalView
                       {
                           ID = m.ID,
                           CircularName = m.CircularName,
                           IsCorrective = m.IsCorrective,
                           PublishTime = m.PublishTime,
                           PublishOrgID = m.PublishOrgID,
                           PublishOrg = OrgInfoService.GetOrgNameByID(m.PublishOrgID),
                           PublishUserID = m.PublishUserID,
                           PublishUser = UserInfoService.GetUserNameByID(m.PublishUserID),
                           IsDeleted = m.IsDeleted,
                           AddDate = m.AddDate,
                           Content = m.Content,
                           LoginUserID = SystemData.Instance.CurrentUser.ID
                       };
            var result = new { total = EnvironmentalService.Environmentals.Count(), rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            OperationResult exeResult = new OperationResult(OperationResultType.Success);
            Guid guidID = id.ToGuid();
            var record = EnvironmentalService.Environmentals.FirstOrDefault(m => m.ID == guidID);
            if (record != null)
            {
                //如果当前登录用户不是发布人，则不允许删除
                if (!SystemData.Instance.CurrentUser.ID.Equals(record.PublishUserID))
                {
                    exeResult = new OperationResult(OperationResultType.Warning, "非发布人不允许删除记录");
                }
                else
                {
                    exeResult = EnvironmentalService.Delete(guidID);
                    if (exeResult.ResultType == OperationResultType.Success)
                    {
                        var docDeleteResult = DocumentService.DeleteByInstanceID(guidID);
                        if (docDeleteResult == true)
                        {
                            exeResult.Message += "，已删除关联附件记录";
                        }
                    }
                }
            }
            return Json(exeResult);
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(string id)
        {
            EnvironmentalView model = new EnvironmentalView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = EnvironmentalService.Environmentals.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record.CopyTo<EnvironmentalView>();
                    model.PublishUser = UserInfoService.GetUserInfoByID(model.PublishUserID).UserName;
                    //model.PublishOrg = OrgInfoService.GetOrgNameByID(model.PublishOrgID);

                    //整改标段
                    if (!String.IsNullOrEmpty(model.CorrectiveSectionIDs))
                    {
                        string[] ids = model.CorrectiveSectionIDs.Split(',');
                        if (ids != null && ids.Length > 0)
                        {
                            List<Guid> guContractIDs = new List<Guid>();
                            foreach (string contractID in ids)
                            {
                                guContractIDs.Add(contractID.ToGuid());
                            }
                            //model.CorrectiveSection = BidInfoService.GetFullSectionNameByID(guSectionids);
                            model.CorrectiveSection = ContractInfoService.GetFullContractNameByID(guContractIDs);
                        }
                    }
                }
            }
            //新增
            else
            {
                model.PublishTime = DateTime.Now;
                model.PublishUserID = SystemData.Instance.CurrentUser.ID;
                model.PublishUser = SystemData.Instance.CurrentUser.UserName;
            }
            return View(model);
        }

        /// <summary>
        /// 新增或编辑（响应）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]  //添加这个是为了防止错误：从客户端中检测到有潜在危险的 Request.Form 值
        public ActionResult EditPost(EnvironmentalView model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            var record = EnvironmentalService.Environmentals.FirstOrDefault(m => m.ID == model.ID);

            //新增
            if (record == null)
            {
                record = model.CopyTo<Environmental>();
                result = EnvironmentalService.Add(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //修改
            else
            {
                record = model.CopyTo<Environmental>();
                result = EnvironmentalService.Modify(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }

            SaveSystemMessage(record);

            //return View();
            return Json(result, "text/html");
        }

        private void SaveSystemMessage(Environmental model)
        {
            if (!string.IsNullOrEmpty(model.CorrectiveSectionIDs))
            {
                List<SystemProcessMessageView> saveList = new List<SystemProcessMessageView>();
                string[] correctiveSectionIDArr = model.CorrectiveSectionIDs.Split(',');
                foreach (string selectID in correctiveSectionIDArr)
                {
                    Guid guidID = selectID.ToGuid();
                    ContractInfo contractInfo = ContractInfoService.ContractInfos.FirstOrDefault(c => c.ID == guidID);
                    if (contractInfo != null)
                    {
                        AddSystemMeaage(contractInfo.CorrespondenceUnit, model.ID, "Contract", contractInfo.ID, saveList);
                    }
                    else
                    {
                        CommonContractInfo commonContractInfo = CommonContractInfoService.CommonContractInfos.FirstOrDefault(c => c.ID == guidID);
                        if (commonContractInfo != null && commonContractInfo.CorrespondenceUnit != Guid.Empty)
                        {
                            AddSystemMeaage(commonContractInfo.CorrespondenceUnit, model.ID, "CommonContract", commonContractInfo.ID, saveList);
                        }
                    }
                }
                SystemProcessMessageService.SaveSystemProcessMessage(saveList);
            }
        }

        private void AddSystemMeaage(Guid orgID, Guid recordID, string refType, Guid refID, List<SystemProcessMessageView> saveList)
        {
            var lstProcessUser = from ug in UserOrgService.UserOrgs
                                 join u in UserInfoService.Users
                                 on ug.UserID equals u.ID
                                 where ug.OrgID == orgID && ug.IsPurviewAdmin == true
                                 select u;
            foreach (var user in lstProcessUser)
            {
                SystemProcessMessageView add = new SystemProcessMessageView();
                add.ID = Guid.NewGuid();
                add.MessageType = "SafetyCircular";
                add.RecordID = recordID;
                add.RefType = refType;
                add.RefID = refID;
                add.ProcessUser = user.UserName;
                add.SendUser = User.Identity.Name;
                add.SendTime = DateTime.Now;
                saveList.Add(add);
            }
        }

        /// <summary>
        /// 根据通报ID获取通报名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetCircularNameByID(Guid id)
        {
            string result = string.Empty;
            result = EnvironmentalService.GetCircularNameByID(id);
            return result;
        }

        /// <summary>
        /// 选择通报
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseCircular()
        {
            return View();
        }

        /// <summary>
        /// 选择通报（Post）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChooseCircularPost()
        {
            var result = new OperationResult(OperationResultType.Success, "选择成功");
            return Json(result, "text/html");
        }

        /// <summary>
        /// 通报列表明细列
        /// </summary>
        /// <returns></returns>
        public ActionResult CircularDataGridDetail(string id)
        {
            EnvironmentalView model = new EnvironmentalView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = EnvironmentalService.Environmentals.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record.CopyTo<EnvironmentalView>();
                    model.PublishUser = UserInfoService.GetUserInfoByID(model.PublishUserID).UserName;
                    //model.PublishOrg = OrgInfoService.GetOrgNameByID(model.PublishOrgID);

                    //整改标段
                    if (!String.IsNullOrEmpty(model.CorrectiveSectionIDs))
                    {
                        string[] ids = model.CorrectiveSectionIDs.Split(',');
                        if (ids != null && ids.Length > 0)
                        {
                            List<Guid> guContractids = new List<Guid>();
                            foreach (string contractID in ids)
                            {
                                guContractids.Add(contractID.ToGuid());
                            }
                            //model.CorrectiveSection = BidInfoService.GetFullSectionNameByID(guSectionids);
                            model.CorrectiveSection = ContractInfoService.GetFullContractNameByID(guContractids);
                        }
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 预览通报
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Preview(string id)
        {
            EnvironmentalView model = new EnvironmentalView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = EnvironmentalService.Environmentals.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record.CopyTo<EnvironmentalView>();
                    model.PublishUser = UserInfoService.GetUserInfoByID(model.PublishUserID).UserName;
                    model.PublishOrg = OrgInfoService.GetOrgNameByID(model.PublishOrgID);

                    //整改标段
                    if (!String.IsNullOrEmpty(model.CorrectiveSectionIDs))
                    {
                        string[] ids = model.CorrectiveSectionIDs.Split(',');
                        if (ids != null && ids.Length > 0)
                        {
                            List<Guid> guContractids = new List<Guid>();
                            foreach (string contractID in ids)
                            {
                                guContractids.Add(contractID.ToGuid());
                            }
                            //model.CorrectiveSection = BidInfoService.GetFullSectionNameByID(guSectionids);
                            model.CorrectiveSection = ContractInfoService.GetFullContractNameByID(guContractids);
                        }
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 预览详细通报
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Detail(string id)
        {
            return Preview(id);
        }
    }
}